package com.javafactroy.kunlong.data.valueobj;

import cn.hutool.core.annotation.AnnotationUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

import org.springframework.stereotype.Service;

import javax.persistence.Column;
import java.lang.reflect.Field;

@Service
public class GeneralFieldRefModel {

    public <T> Field[] refProps(Class<T> cls) {
        return ReflectUtil.getFields(cls);
    }

    /*prop->field*/
    public <T> BiMap<String, String> refProp2FieldsMap(Class<T> cls) {
        Field[] fields = refProps(cls);

        BiMap<String, String> biMap = HashBiMap.create();
        for (Field field : fields) {
            Column column = AnnotationUtil.getAnnotationValue(field.getClass(), Column.class);
            if (column == null) {
                biMap.put(field.getName(), StrUtil.toUnderlineCase(field.getName()));
            } else {
                biMap.put(field.getName(), column.name());
            }
        }
        return biMap;
    }
}
